from django.conf import settings
from django.core.cache import cache

def init_permission(current_user,request):
    '''正向查找(条件)之多对多'''
    permission_queryset = current_user.roles.filter(permissions__isnull=False).values('permissions__id',
                                                                                      'permissions__authName',
                                                                                      'permissions__url',
                                                                                      'permissions__menu_id',
                                                                                      'permissions__menu__menuName',
                                                                                      'permissions__menu__icon').distinct()
    print('permission_queryset',permission_queryset)
    permission_list = []
    menu_dict = {}
    menu_id_list = []
    temp = {}
    for item in permission_queryset:
        # print('-->item',item)
        permission_list.append(item['permissions__url'])
        menu_id = item['permissions__menu_id']
        if not menu_id:
            continue

        node = {
            'id': item['permissions__id'],
            'authName': item['permissions__authName'],
            'url': item['permissions__url'],
        }
        if menu_id in menu_dict:
            menu_dict[menu_id]['children'].append(node)
        else:
            menu_id_list.append(menu_id)
            # print('menu_id_list', menu_id_list)
            menu_dict[menu_id] = {
                'id':item['permissions__menu_id'],
                'authName':item['permissions__menu__menuName'],
                'icon':item['permissions__menu__icon'],
                'children':[node]
            }
            # menu_list.append(temp)
    # request.session.flush()
    request.session[settings.PERMISSION_SESSION_KEY] = permission_list
    request.session[settings.MENU_SESSION_KEY] = menu_dict
    cache.set('menu_dict',menu_dict)
    cache.set('permission_list',permission_list)
    # print(request.session, request._request.session[settings.PERMISSION_SESSION_KEY])
    print('init permission_list',permission_list)
    return permission_list,menu_dict